﻿using Dapr.Client;
using FrontEnd.Model;
using Microsoft.AspNetCore.Mvc;

namespace FrontEnd.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DaprHttpInvokeController : ControllerBase
    {
        private readonly static string _appId = "backend";
        private readonly static string _methodName = "WeatherForecast/Get";
        private readonly ILogger<DaprHttpInvokeController> _logger;
        private readonly DaprClient _daprClient;
        private readonly static HttpClient _httpClient = new();

        public DaprHttpInvokeController(ILogger<DaprHttpInvokeController> logger, DaprClient daprClient)
        {
            _logger = logger;
            _daprClient = daprClient; // (推荐)构造函数注入 DaprClient
        }

        [HttpGet]
        public async Task<ActionResult> GetAsync()
        {
            _logger.LogInformation("构建 HttpClient 调用 BackEnd 服务");
            using var httpClient = DaprClient.CreateInvokeHttpClient();
            var result = await httpClient.GetAsync($"http://{_appId}/{_methodName}");
            var resultContent = string.Format("result is {0} {1}", result.StatusCode, await result.Content.ReadAsStringAsync());
            return Ok(resultContent);
        }

        
        [HttpGet]
        public async Task<ActionResult> Get2Async()
        {
            _logger.LogInformation("构建 DaprClient 调用 BackEnd 服务");
            using var daprClient = new DaprClientBuilder().Build();
            var result = await daprClient.InvokeMethodAsync<IEnumerable<WeatherForecast>>(HttpMethod.Get, _appId, _methodName);
            return Ok(result);
        }

        [HttpGet]
        public async Task<ActionResult> Get3Async()
        {
            _logger.LogInformation("构造函数 DI 注入 daprClient 调用 BackEnd 服务");
            var result = await _daprClient.InvokeMethodAsync<IEnumerable<WeatherForecast>>(HttpMethod.Get, _appId, _methodName);
            return Ok(result);
        }


        [HttpGet]
        public async Task<ActionResult> Get4Async()
        {
            _logger.LogInformation("构建 HttpClient 调用 BackEnd 服务");
            var result = await _httpClient.GetAsync("http://localhost:5000/WeatherForecast/Get");
            var resultContent = string.Format("result is {0} {1}", result.StatusCode, await result.Content.ReadAsStringAsync());
            return Ok(resultContent);
        }
    }
}
